package main.java.DMDE.persistence;

import java.util.UUID;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import main.java.DMDE.model.*;
import main.java.DMDE.model.relationships.*;
import main.java.common.IXmlManager;

public class RelationshipComponentXmlManager implements IXmlManager<RelationshipComponent> {

	public Element getElementFromItem(RelationshipComponent relationshipComponent, Document document) {
		Element relationshipComponentElement = document.createElement("relationshipComponent");
		relationshipComponentElement.setAttribute("id", relationshipComponent.getEntity().getId().toString());
		if (relationshipComponent.getMinCardinality() != null)
			relationshipComponentElement.setAttribute("min", relationshipComponent.getMinCardinality().getDesc());
		if (relationshipComponent.getMaxCardinality() != null)
			relationshipComponentElement.setAttribute("max", relationshipComponent.getMaxCardinality().getDesc());
		return relationshipComponentElement;
	}

	@Override
	public RelationshipComponent getItemFromXmlElement(Element element) throws Exception {
		RelationshipComponentProxy relationshipComponent = new RelationshipComponentProxy();
		relationshipComponent.id  = UUID.fromString(element.getAttribute("id"));
		relationshipComponent.maxCardinality = getCardinality(element.getAttribute("max"));
		relationshipComponent.minCardinality = getCardinality(element.getAttribute("min"));
		return relationshipComponent;
	}
	
	private CardinalityValues getCardinality(String cardinality) {
		if (CardinalityValues.CERO.getDesc().equals(cardinality)) {
			return CardinalityValues.CERO;
		}
		if (CardinalityValues.MANY.getDesc().equals(cardinality)) {
			return CardinalityValues.MANY;
		}
		if (CardinalityValues.ONE.getDesc().equals(cardinality)) {
			return CardinalityValues.ONE;
		}
		return null;
	}
}
